// 异步计算文件大小
const fs = require('fs')
const path = require('path');

const { promisify } = require('util')
const stat = promisify(fs.stat)
const readdir = promisify(fs.readdir)

async function calcFileSizeAsync (dirPath, cb) {
  let fileSize = 0

  async function getFileSize (dirPath) {
    const statObj = await stat(dirPath)
    if (statObj.isDirectory()) {
      const files = await readdir(dirPath)
      const dirs = files.map(item => path.join(dirPath, item))
      for (let i = 0; i < dirs.length; i++) {
        await getFileSize(dirs[i])
      }
    } else {
      fileSize += statObj.size
    }
  }
  await getFileSize(dirPath)
  cb && cb(fileSize)
}

calcFileSizeAsync('test', size => {
  console.log("异步计算文件大小：" + size)
})
